<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\FormException;
use App\Http\Controllers\LayuiController;
use App\Models\Goods;
use App\Models\GoodsHome;
use App\Models\GoodsHomeRelation;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class GoodsHomeController extends Controller
{
    /**
     * 商品模块管理列表
     * @name index
     * @param void
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/23 16:03
     */
    public function index(){
        $data = GoodsHome::get();
        return view('Admin.goodsHome.index',['data' => $data]);
    }


    /**
     * 获取商品列表
     * @name goodstable
     * @param array
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/21 16:29
     */
    public function goodstable(Request $request){

        $module = $request->input('module',0);

        $moduleInfo = GoodsHome::find($module);

        /* 查询品牌列表 */
        $brandList = DB::table('goods_brand')
            ->select('id','name')
            ->get()
            ->mapWithKeys(function($item){
                return [$item->id => $item->name];
            });

        /* 数据查询 */
        $preData = GoodsHomeRelation::where('home_id',$module)
            ->orderBy('sort','desc')
            ->paginate($request->get('limit',30));

        $minSort = GoodsHomeRelation::where('home_id',$module)->min('sort') ?? 0;
        $maxSort = GoodsHomeRelation::where('home_id',$module)->max('sort') ?? 0;

        /* 数据处理 */
        $data = $preData->map(function($item)use($brandList,$minSort,$maxSort,$moduleInfo){
            return [
                'id'         => $item->id,
                'home_id'    => $item->home_id,
                'good_id'    => $item->goodInfo->id ?? 0,
                'photo'      => $item->goodInfo->photo ?? '',
                'goods_name' => $item->goodInfo->goods_name ?? '',
                'sku'        => $item->goodInfo->sku ?? '',
                'brand'      => $brandList[$item->goodInfo->brand ?? ''] ?? '',
                'status'     => Goods::STATUS[$item->goodInfo->status ?? ''] ?? '',
                'price'      => $item->goodInfo->price ?? 0,
                'sort'       => $item->sort,
                'min_sort'   => $minSort,
                'max_sort'   => $maxSort,
                'home_status'=> $moduleInfo->status ?? GoodsHome::STATUS_CLOSE
            ];
        });

        return LayuiController::tableJson($data,0,$preData->total());
    }

    /**
     * 模块编辑
     * @name update
     * @param void
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/24 15:47
     */
    public function update(Request $request,$id){
        $payload = $request->only('module');
        $payload['status'] = $request->input('status',GoodsHome::STATUS_CLOSE);
        Validator::make($payload, [
            'module'  => 'required|max:8',
        ],[
            'module.required'   => '请输入活动名称',
            'module.max'        => '活动名称最多8个字',
        ])->validate();

        DB::beginTransaction();

        try{
            $model = GoodsHome::findOrFail($id);

            $model->module = $payload['module'];
            $model->status = $payload['status'];

            $model->save();

        }catch (\Exception $exception){
            DB::rollBack();
            throw new FormException(App::environment('local') ? $exception->getMessage() : '保存失败' );
        }
        DB::commit();
        return $this->getResponse('保存成功');
    }

    /**
     * 获取商品列表
     * @name goodstable
     * @param array
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/21 16:29
     */
    public function goodstableAll(Request $request){

        $payload = $request->all();

        /* 查询已存在商品 */
        $home_id = $request->input('home_id',0);
        $goodIdIN = GoodsHomeRelation::where('home_id',$home_id)->pluck('good_id');
        /* 查询品牌列表 */
        $brandList = DB::table('goods_brand')
            ->select('id','name')
            ->get()
            ->mapWithKeys(function($item){
                return [$item->id => $item->name];
            });
        $preData = Goods::when($keywords = array_get($payload,'keywords'),function($query)use($keywords){
                $query->where(function($query)use($keywords){
                    $query->whereHas('brandInfo', function ($query)use($keywords) {
                            $query->where('name', 'like', "%$keywords%");
                        })
                        ->orWhere('goods_name', 'like', "%$keywords%")
                        ->orWhere('title','like', "%$keywords%")
                        ->orWhere('sku','like', "%$keywords%");
                });
            })
            ->whereNotIn('id',$goodIdIN)
            ->where('status',Goods::STATUS_OPEN)
            ->orderBy('sort','desc')
            ->paginate($request->get('limit',30));

        $data = $preData->map(function($item)use($brandList){
            return [
                'good_id'    => $item->id,
                'photo'      => $item->photo,
                'goods_name' => $item->goods_name,
                'sku'        => $item->sku,
                'brand'      => $brandList[$item->brand] ?? '',
                'price'      => $item->price,
            ];
        });

        return LayuiController::tableJson($data,0,$preData->total());
    }

    /**
     * 添加商品保存
     * @name insertGood
     * @param array
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/24 16:48
     */
    public function insertGood(Request $request,$id){
        $payload = $request->only('selected_good_id');

        Validator::make($payload, [
            'selected_good_id'  => 'required',
        ],[
            'selected_good_id.required'   => '请选择商品',
        ])->validate();

        DB::beginTransaction();

        try{
           /* 查询最大排序 */
            $maxSort = GoodsHomeRelation::where('home_id',$id)->max('sort') ?? 0;

            /* 循环组建插入数组 */
            $saveData = [];
            $goodIDArr = explode(',',trim($payload['selected_good_id'],','));
            foreach($goodIDArr as $good_id){
                $saveData[] = [
                    'home_id'   => $id,
                    'good_id'   => $good_id,
                    'sort'      => ++$maxSort
                ];
            }
            DB::table('goods_home_relation')->insert($saveData);

        }catch (\Exception $exception){
            DB::rollBack();
            throw new FormException(App::environment('local') ? $exception->getMessage() : '保存失败' );
        }
        DB::commit();
        return $this->getResponse('保存成功');
    }

    /**
     * 解绑活动商品
     * @name deleteGood
     * @param \Illuminate\Http\JsonResponse
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/24 17:09
     */
    public function deleteGood(Request $request,$id)
    {
        DB::beginTransaction();
        try{
            /* 查询该ID下数据 */
            $model = GoodsHomeRelation::findOrFail($id);
            /* 修改删除ID下数据排序 */
            DB::table('goods_home_relation')->where('home_id',$model->home_id)
                ->where('sort','>',$model->sort)
                ->decrement('sort');
            /* 删除数据 */
            $model->delete();
        }catch (\Exception $exception){
            DB::rollBack();
            throw new FormException(App::environment('local') ? $exception->getMessage() : '操作失败' );
        }
        DB::commit();
        return $this->getResponse('操作成功');
    }

    /**
     * 修改商品排序
     * @name sort
     * @param \Illuminate\Http\JsonResponse
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/5/25 9:26
     */
    public function sort(Request $request,$id)
    {
        $payload = $request->only('tag');

        Validator::make($payload, [
            'tag'  => 'required|in:up,down',
        ],[
            'tag.required'   => '请选择排序商品',
            'tag.in'         => '请选择排序方式',
        ])->validate();

        DB::beginTransaction();
        try{
            /* 查询该ID下数据 */
            $model = GoodsHomeRelation::findOrFail($id);
            /* tag=up 将它上序数据对换 tag=down  将它下序数据对换 */
            if($payload['tag'] == 'up'){
                DB::table('goods_home_relation')->where('home_id',$model->home_id)->where('sort',++$model->sort)->decrement('sort');
            }else{
                DB::table('goods_home_relation')->where('home_id',$model->home_id)->where('sort',--$model->sort)->increment('sort');
            }
            $model->save();
        }catch (\Exception $exception){
            DB::rollBack();
            throw new FormException(App::environment('local') ? $exception->getMessage() : '操作失败' );
        }
        DB::commit();
        return $this->getResponse('操作成功');
    }

}
